//
//  LGTPhoneLoginVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/12.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD

class LGTPhoneLoginVC: LGTBaseVC, UITextViewDelegate {

    var _loginType:Int = 0
    var timer:Timer?
    var timeIndex:Int = 0
    var loginType:Int{
        get{
            return _loginType
        }set{
            _loginType = newValue
        }
    }
    
    var pdwayLoginBtn:UIButton?
    var codewayLoginBtn:UIButton?
    var lineView:UIImageView? //滑动线
    
    var codeLoginView:UIView? //验证码视图
    var codePhoneTextField:UITextField? // 验证码手机号视图
    var codeTextField:UITextField? // 验证码视图
    var codeBtn:LGTButton? //获取验证码
    var codeLoginBtn:UIButton?
    var agrreenTextView:UITextView? //用户注册协议
    
    var pdLoginView:UIView? //密码视图
    var accountTextField:UITextField? //账号
    var passwordTextField:UITextField? //密码
    var eyeBtn:LGTButton?  //加密
    var passwordLoginBtn:UIButton?
    var agrreenTextView2:UITextView? //用户注册协议
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //self.setUI()
        self.loginWayChange(way: self.loginType)
        self.addNote()
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "手机号登录", back: true)
        
        self.codewayLoginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "短信登录", font: Font_Normal_15, color: NavTitleColor, selectedColor: YellowColor, dW: CGFloat(KRate * 10), dH: CGFloat(KRate * 10))
        self.codewayLoginBtn!.tag = 0
        self.view.addSubview(self.codewayLoginBtn!)
        self.codewayLoginBtn!.snp.makeConstraints { (make) in
            make.right.equalTo(self.view.snp_centerXWithinMargins).offset(-KRate * 36)
            make.height.equalTo(KRate * 15)
            make.width.equalTo(KRate * 65)
            make.top.equalTo(KRate * 38 + NavBarH)
        }
        
        self.pdwayLoginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "密码登录", font: Font_Normal_15, color: NavTitleColor, selectedColor: YellowColor, dW: CGFloat(KRate * 10), dH: CGFloat(KRate * 10))
        self.view.addSubview(self.pdwayLoginBtn!)
        self.pdwayLoginBtn?.tag = 1
        self.pdwayLoginBtn!.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp_centerXWithinMargins).offset(KRate * 36)
            make.height.equalTo(KRate * 15)
            make.width.equalTo(KRate * 65)
            make.top.equalTo(KRate * 38 + NavBarH)
        }
        
        self.lineView = LGTViewCreateUtil.share.createImageViewCorner(corner: CGFloat(KRate * 1))
        self.lineView?.backgroundColor = YellowColor
        self.view.addSubview(self.lineView!)
        
        let lineX = KScreenW/2 - SizeFitFloat(101) + (SizeFitFloat(65 - 12))/2
        let lineY = SizeFitFloat(61.0) +  CGFloat(NavBarH)
        self.lineView?.frame = CGRect.init(x: CGFloat(lineX), y: lineY, width: SizeFitFloat(12), height: SizeFitFloat(2))
        
        self.codewayLoginBtn!.addTarget(self, action:#selector(loginWayAction), for: UIControl.Event.touchUpInside)
        self.pdwayLoginBtn!.addTarget(self, action:#selector(loginWayAction), for: UIControl.Event.touchUpInside)
        
        
        // 验证码登陆视图
        self.codeLoginView = UIView.init()
        //self.codeLoginView?.backgroundColor = UIColor.orange
        self.view.addSubview(self.codeLoginView!)
        self.codeLoginView?.snp.makeConstraints({ (make) in
            make.bottom.left.right.equalTo(0)
            make.top.equalTo(self.pdwayLoginBtn!.snp_bottomMargin).offset(KRate * 75)
        })
        
        let phoneLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: 14, text: "+86")
        self.codeLoginView?.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 76)
            make.height.equalTo(KRate * 14)
            make.top.equalTo(0)
        }
        
        self.codePhoneTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "仅支持中国大陆手机号", textColor: TextColor, limitCout: 11)
        self.codeLoginView!.addSubview(self.codePhoneTextField!)
        self.codePhoneTextField!.snp.makeConstraints { (make) in
            make.left.equalTo(phoneLabel.snp_rightMargin).offset(KRate * 22)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 160)
            make.centerY.equalTo(phoneLabel)
        }
        //self.codePhoneTextField?.text = UserModel.share?.phone
        
        let line:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.codeLoginView!.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(phoneLabel.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.codeTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "请输入验证码", textColor: TextColor, limitCout: 6)
        self.codeLoginView!.addSubview(self.codeTextField!)
        self.codeTextField!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 20)
            make.width.equalTo(KRate * 90)
            make.top.equalTo(line).offset(KRate * 24)
        }
        
        
        self.codeBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "获取验证码", font: Font_Normal_12, color: DisableColor, selectedColor: DisableColor)
        self.codeBtn?.isUserInteractionEnabled = false
        self.codeLoginView!.addSubview(self.codeBtn!)
        self.codeBtn?.snp.makeConstraints({ (make) in
            make.right.equalTo(-KRate * 78)
            make.width.equalTo(KRate * 62)
            make.height.equalTo(14)
            make.centerY.equalTo(self.codeTextField!)
        })
        self.codeBtn?.addTarget(self, action: #selector(sendCodeAction), for: UIControl.Event.touchUpInside)
        
        let line2:UIImageView = LGTViewCreateUtil.share.createLineView()
        self.codeLoginView!.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.codeTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.codeLoginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "登录", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:CGFloat(KRate * 20))
        self.codeLoginBtn?.backgroundColor = DisableColor
        self.codeLoginView!.addSubview(self.codeLoginBtn!)
        self.codeLoginBtn!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(KRate * -75)
            make.height.equalTo(40 * KRate)
            make.top.equalTo(line2.snp_bottomMargin).offset(KRate * 39)
        }
        self.codeLoginBtn?.isUserInteractionEnabled = false
        self.codeLoginBtn?.addTarget(self, action: #selector(codeLoginAction), for: UIControl.Event.touchUpInside)
        
        self.agrreenTextView = LGTViewCreateUtil.share.createAgreenText()
        self.agrreenTextView?.delegate = self;
        self.codeLoginView?.addSubview(self.agrreenTextView!)
        self.agrreenTextView?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.codeLoginBtn!)
            make.height.equalTo(KRate * 30)
            make.width.equalTo(KRate * 240)
            make.top.equalTo(self.codeLoginBtn!.snp_bottomMargin).offset(KRate * 10)
        })
        
        //密码登陆视图
        self.pdLoginView = UIView.init()
        //self.pdLoginView?.backgroundColor = UIColor.orange
        self.view.addSubview(self.pdLoginView!)
        self.pdLoginView?.snp.makeConstraints({ (make) in
            make.bottom.left.right.equalTo(0)
            make.top.equalTo(self.pdwayLoginBtn!.snp_bottomMargin).offset(KRate * 75)
        })
        
        let accountLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: CGFloat(KRate * 14), text: "账号")
        //accountLabel.backgroundColor = UIColor.red
        self.pdLoginView?.addSubview(accountLabel)
        accountLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 14)
            make.top.equalTo(KRate * 0)
            make.width.equalTo(KRate * 30)
        }
        
        self.accountTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.numberPad, placeholder: "请输入账号", textColor: TextColor, limitCout: 11)
        self.pdLoginView?.addSubview(self.accountTextField!)
        //self.accountTextField?.text = UserModel.share?.phone
        //self.accountTextField?.backgroundColor = UIColor.orange
        self.accountTextField?.snp.makeConstraints({ (make) in
            make.left.equalTo(accountLabel.snp_rightMargin).offset(KRate * 14)
            make.height.equalTo(KRate * 20)
            make.centerY.equalTo(accountLabel)
            make.right.equalTo(KRate * -100)
        })
        
        let line3 = LGTViewCreateUtil.share.createLineView()
        self.pdLoginView?.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(accountLabel.snp_bottomMargin).offset(KRate * 14)
        }
        
        self.passwordTextField = LGTViewCreateUtil.share.createLGTTextFied(font: Font_Normal_14, keyBoardType: UIKeyboardType.default, placeholder: "请输入密码", textColor: TextColor, limitCout: 20)
        self.passwordTextField?.isSecureTextEntry = true
        self.pdLoginView?.addSubview(self.passwordTextField!)
        
        let psLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: CGFloat(KRate * 14), text: "密码")
        self.pdLoginView?.addSubview(psLabel)
        psLabel.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.height.equalTo(KRate * 14)
            //make.top.equalTo(line3.snp_bottomMargin).offset(KRate * 24)
            make.centerY.equalTo(self.passwordTextField!)
            make.width.equalTo(KRate * 30)
        }

        self.passwordTextField?.snp.makeConstraints({ (make) in
            make.left.equalTo(psLabel.snp_rightMargin).offset(KRate * 14)
            make.top.equalTo(line3).offset(KRate * 24)
            make.height.equalTo(KRate * 20)
            //make.centerY.equalTo(psLabel)
            make.right.equalTo(KRate * -100)
        })

        self.eyeBtn = LGTViewCreateUtil.share.createLGTButton(image: "open_eyes", selected: "closedeyes", dW: CGFloat(KRate * 5), dH: CGFloat(KRate * 5))
        self.pdLoginView?.addSubview(self.eyeBtn!)
        self.eyeBtn?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.passwordTextField!.snp_rightMargin).offset(KRate * 6)
            make.width.equalTo(KRate * 15)
            make.height.equalTo(KRate * 10)
            make.centerY.equalTo(psLabel)
        })
        self.eyeBtn?.addTarget(self, action: #selector(openeyeAction), for: UIControl.Event.touchUpInside)

        let line4 = LGTViewCreateUtil.share.createLineView()
        self.pdLoginView?.addSubview(line4)
        line4.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(-KRate * 75)
            make.height.equalTo(1)
            make.top.equalTo(self.passwordTextField!.snp_bottomMargin).offset(KRate * 14)
        }
        
        let forgetBtn:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "忘记密码？", font: Font_Normal_12, color: YellowColor, selectedColor: YellowColor, dW: 5, dH: 5)
        forgetBtn.addTarget(self, action: #selector(forgetAction), for: UIControl.Event.touchUpInside)
        self.pdLoginView?.addSubview(forgetBtn)
        forgetBtn.snp.makeConstraints { (make) in
            make.height.equalTo(KRate * 14)
            make.width.equalTo(KRate * 72)
            make.left.equalTo(KRate * 75)
            make.top.equalTo(line4).offset(KRate * 10)
        }
        
        self.passwordLoginBtn = LGTViewCreateUtil.share.createTextLGTButton(title: "登录", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:CGFloat(KRate * 20))
        self.passwordLoginBtn?.backgroundColor = DisableColor
        self.pdLoginView!.addSubview(self.passwordLoginBtn!)
        self.passwordLoginBtn!.snp.makeConstraints { (make) in
            make.left.equalTo(KRate * 75)
            make.right.equalTo(KRate * -75)
            make.height.equalTo(40 * KRate)
            make.top.equalTo(forgetBtn.snp_bottomMargin).offset(KRate * 15)
        }
        self.passwordLoginBtn?.isUserInteractionEnabled = false
        self.passwordLoginBtn?.addTarget(self, action: #selector(passwordLoginAction), for: UIControl.Event.touchUpInside)
        
        self.agrreenTextView2 = LGTViewCreateUtil.share.createAgreenText()
        self.agrreenTextView2?.delegate = self;
        self.pdLoginView?.addSubview(self.agrreenTextView2!)
        self.agrreenTextView2?.snp.makeConstraints({ (make) in
            make.left.equalTo(self.codeLoginBtn!)
            make.height.equalTo(KRate * 30)
            make.width.equalTo(KRate * 240)
            make.top.equalTo(self.passwordLoginBtn!.snp_bottomMargin).offset(KRate * 10)
        })
    }
    
    @objc func forgetAction(){
        let forgetVC = LGTForgetPasswordVC()
        self.navigationController?.pushViewController(forgetVC, animated: true)
    }
    
    @objc func loginWayAction(button:UIButton){
        self.loginWayChange(way: button.tag)
        self.view.endEditing(true)
    }
    
    func loginWayChange(way:Int){
        self.loginType = way
        let firstState:Bool = way == 0 ? true:false
        self.codewayLoginBtn!.isSelected = firstState
        self.pdwayLoginBtn!.isSelected = !firstState
        
        self.codeLoginView?.isHidden = !firstState
        self.pdLoginView?.isHidden = firstState
        
        var frame = self.lineView!.frame
        var point = frame.origin
        let lineX = (KScreenW/2 - SizeFitFloat(101)) + (SizeFitFloat(65 - 12))/2 + SizeFitFloat(137.0 * Double(way))
        point.x = lineX
        frame.origin = point
        self.lineView?.frame = frame
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    //点击跳转
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        let url = "\(AppModel.share?.m_host ?? "")/\(Agreen_Html_URl)"
        let webVC = LGTBaseWebVC()
        webVC.url = url
        self.navigationController?.pushViewController(webVC, animated: true)
        return false
    }
    
    @objc func openeyeAction(){
        self.eyeBtn?.isSelected = !self.eyeBtn!.isSelected
        self.passwordTextField?.isSecureTextEntry = self.eyeBtn!.isSelected
    }
    
    @objc func sendCodeAction(){
        if self.timeIndex > 0{
            return
        }
        
        if self.codePhoneTextField?.text?.count != 11{
            WisdomHUD.showError(text: "请输入正确的手机号码")
            return
        }
        
        weak var weakSelf = self
        let params:Dictionary<String, Any> = ["phone": self.codePhoneTextField!.text ?? "",
                      "type": 1]
        LGTHttpUtil.httpUtil.requestData(url: Send_Code_URL, param: params, showMessage: true, success: { (json) in
            let state:Int = json["state"] as! Int
            if state == 0{
                weakSelf!.timeIndex = 60
                weakSelf!.createTimer()
            }
        }) { (json) in
          
        }
    }
    
    func createTimer(){
        if self.timeIndex <= 0{
            return
        }
        
        self.timer?.invalidate()
        weak var weakSelf = self
        self.timer = Timer.init(timeInterval: 1, repeats: true, block: { (timer:Timer) in
            weakSelf?.timeIndex -= 1
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.normal)
            weakSelf?.codeBtn?.setTitle("\(weakSelf!.timeIndex)S", for: UIControl.State.selected)
            if weakSelf!.timeIndex <= 0{
                weakSelf?.closeTimer()
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.normal)
                weakSelf?.codeBtn?.setTitle("获取验证码", for: UIControl.State.selected)
            }
        })
        
        RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fire()
    }
    
    func closeTimer(){
        self.timer?.invalidate()
    }
    
    @objc func passwordLoginAction(){
        //账号或密码不能为空
        self.view.endEditing(true)
        if self.accountTextField?.text?.count  == 0 || self.passwordTextField?.text?.count == 0{
            WisdomHUD.showError(text: "账号或密码不能为空")
            return
        }
        
        //请输入6~20位数字或字母的密码
        //        let params:Dictionary<String, Any> = ["phone": self.codePhoneTextField!.text ?? "",
        //"type": 1]
        let pass:String = LGTOCBaseUtil.md5(forLower32Bite: self.passwordTextField!.text ?? "")
        weak var weakSelf = self
        self.view.isUserInteractionEnabled = false
        let param:Dictionary<String, Any> = ["phone": self.accountTextField!.text ?? "",
                                             "password": pass,
                                             "type": 1]
        WisdomHUD.showLoading(text: "")
        LGTHttpUtil.httpUtil.requestData(url: PassWord_Code_URL, param: param, showMessage:false, success: { (json) in
             LGTViewUtil.share.loginAction(nav: weakSelf?.navigationController, json: json)
            weakSelf!.view.isUserInteractionEnabled = true
        }) { (json) in
            LGTViewUtil.share.loginAction(nav: weakSelf?.navigationController, json: json)
            weakSelf!.view.isUserInteractionEnabled = true
        }
    }
    
    @objc func codeLoginAction(){
        self.view.endEditing(true)
        if self.codeTextField?.text?.count  == 0 || self.codePhoneTextField?.text?.count == 0{
            WisdomHUD.showError(text: "手机号或验证码不能为空")
            return
        }
        
        let param:Dictionary<String, Any> = ["phone": self.codePhoneTextField?.text ?? "",
                                             "type": 1,
                                             "code": self.codeTextField?.text ?? ""]
        weak var weakSelf = self
        self.view.isUserInteractionEnabled = false
        WisdomHUD.showLoading(text: "")
        LGTHttpUtil.httpUtil.requestData(url: Login_Code_URL, param: param, showMessage:false, success: { (json) in
            LGTViewUtil.share.loginAction(nav: weakSelf?.navigationController, json: json)
            weakSelf?.view.isUserInteractionEnabled = true
        }) { (json) in
            LGTViewUtil.share.loginAction(nav: weakSelf?.navigationController, json: json)
            weakSelf?.view.isUserInteractionEnabled = true
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.closeTimer()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createTimer()
    }
    
    func addNote(){
        self.codePhoneTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.codeTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.accountTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
        self.passwordTextField?.addTarget(self, action: #selector(textFieldChange), for: UIControl.Event.editingChanged)
    }
    
    @objc private func textFieldChange(textField:UITextField){
        //验证码可不可以登录验证
        if self.codePhoneTextField?.text?.count == 11 && (self.codeTextField?.text?.count ?? 0 > 0){
            self.codeLoginBtn?.backgroundColor = YellowColor
            self.codeLoginBtn?.isUserInteractionEnabled = true
        }else{
            self.codeLoginBtn?.backgroundColor = DisableColor
            self.codeLoginBtn?.isUserInteractionEnabled = false
        }
        
        //验证码可点击验证
        if self.codePhoneTextField?.text?.count == 11{
            self.codeBtn?.isUserInteractionEnabled = true
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(YellowColor, for: UIControl.State.selected)
        }else{
            self.codeBtn?.isUserInteractionEnabled = false
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.normal)
            self.codeBtn?.setTitleColor(DisableColor, for: UIControl.State.selected)
        }
        
        //密码登录
        if self.accountTextField?.text?.count == 11 && (self.passwordTextField?.text?.count ?? 0 > 0){
            self.passwordLoginBtn?.backgroundColor = YellowColor
            self.passwordLoginBtn?.isUserInteractionEnabled = true
        }else{
            self.passwordLoginBtn?.backgroundColor = DisableColor
            self.passwordLoginBtn?.isUserInteractionEnabled = false
        }
    }
    
    deinit {
        self.closeTimer()
        
        
    }
}
